//////////////////////////////////////
///file: arbitrator.v
///Author: Qyw
//////////////////////////////////////

module arbitrator(//input
				clk,
				rst_n,
				ch_req,
				sram_ack,
				ch_addr,
				sram_busy,
				//output
				sram_rd,
				sram_addr,
				ch_ack
			);

input			clk,
				rst_n;
input	[7:0]	ch_req; //all 8 channels sram reqs
input	[103:0]	ch_addr;	//channels addr req 
input			sram_ack, //sram ack signal
				sram_busy;//sram is busy

output	[12:0]	sram_addr; //sram address
output	[7:0]	ch_ack; // 8 channels ack
output			sram_rd; // sram rd singal

reg		[2:0]	ch;
reg		[7:0]	ch_ack;
reg		[12:0]	sram_addr;
reg				ch_oe,
				sram_rd;	

always @(*)
	if(ch_req[0])
		{ch_oe, ch} = 4'b1000;
	else if(ch_req[1])
		{ch_oe, ch} = 4'b1001;
	else if(ch_req[2])
		{ch_oe, ch} = 4'b1010;
	else if(ch_req[3])
		{ch_oe, ch} = 4'b1011;
	else if(ch_req[4])
		{ch_oe, ch} = 4'b1100;
	else if(ch_req[5])
		{ch_oe, ch} = 4'b1101;
	else if(ch_req[6])
		{ch_oe, ch} = 4'b1110;
	else if(ch_req[7])
		{ch_oe, ch} = 4'b1111;
	else
		{ch_oe, ch} = 4'b0000;
	
always @(*)
	if(~ch_oe)
		sram_addr = 13'd0;		
	else
		case(ch)
		3'd0: sram_addr = ch_addr[12:0];
		3'd1: sram_addr = ch_addr[25:13];
		3'd2: sram_addr = ch_addr[38:26];
		3'd3: sram_addr = ch_addr[51:39];
		3'd4: sram_addr = ch_addr[64:52];
		3'd5: sram_addr = ch_addr[77:65];
		3'd6: sram_addr = ch_addr[90:78];
		3'd7: sram_addr = ch_addr[103:91];
		endcase

always @(*)
	if(~ch_oe)
		ch_ack = 8'd0;	
	else
		case(ch)
		3'd0: ch_ack = {7'd0, sram_ack};
		3'd1: ch_ack = {6'd0, sram_ack, 1'b0};
		3'd2: ch_ack = {5'd0, sram_ack, 2'b0};
		3'd3: ch_ack = {4'd0, sram_ack, 3'b0};
		3'd4: ch_ack = {3'd0, sram_ack, 4'b0};
		3'd5: ch_ack = {2'd0, sram_ack, 5'd0};
		3'd6: ch_ack = {1'd0, sram_ack, 6'd0};
		3'd7: ch_ack = {sram_ack, 7'd0};
		endcase

always @(posedge clk or negedge rst_n)
	if(~rst_n)
		sram_rd <= 1'b0; 
	else if(sram_busy)
		sram_rd <= 1'b0;
	else if(ch_oe)
		sram_rd <= 1'b1;

endmodule
